package cn.itcast.usermanage.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.itcast.usermanage.pojo.EasyUIResult;
import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.UserService;

@RequestMapping(value="user")
@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="users")
	public String toUsers(){
		return "users";
	}
	
	@RequestMapping(value="list")
	@ResponseBody
	public EasyUIResult queryUserByPages(@RequestParam("page") Integer page,@RequestParam("rows") Integer size){
		return userService.queryUserByPages(page,size);
	}
	
	
	@RequestMapping(value="/page/{pageName}")
	public String toUserAdd(@PathVariable("pageName") String pageName){
		return pageName;
	}
	
	@RequestMapping(value="/export/excel")
	public String exportExcel(Model model,@RequestParam("page")Integer page, @RequestParam("rows")Integer size){
		EasyUIResult queryUserByPages = userService.queryUserByPages(page,size);
		model.addAttribute("userList", queryUserByPages.getRows());
		return "UserExcel";
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Map<String,Object> toDeleteUser(@RequestParam("ids")String[] ids){
		Map<String, Object> map = new HashMap<String,Object>();
		boolean result;
		try {
			result = userService.deleteUser(ids);
			if(result){
				map.put("status", 200);
			}else
			{
				map.put("status", 500);	
			}
		} catch (Exception e) {
			map.put("status", 500);
			e.printStackTrace();
		}
		return map;
	}
	
	@RequestMapping(value="save")
	@ResponseBody
	public Map<String,Object> AddUser(User user){
		Map<String, Object> map = new HashMap<String,Object>();
		Boolean result = userService.addUser(user);
		if(result){
			map.put("status", 200);
		}else
		{
			map.put("status", 500);
		}
		return map;
	}
	
	@RequestMapping(value="update")
	@ResponseBody
	public Map<String,Object> updateUser(User user){
		Map<String, Object> map = new HashMap<String,Object>();
		Boolean result = userService.updateUser(user);
		if(result){
			map.put("status", 200);
		}else
		{
			map.put("status", 500);
		}
		return map;
	}
	
	
}
